/**
 * Created with JavaScript.
 * User: rgxmg
 * Email: rgxmg@foxmail.com
 * Date: 2020/9/15
 * Time: 11:26
 * 用于处理数据
 * 比如数据的脱敏
 * 时间格式的转换等等
 */
/**
 * 创建手机的隐私性
 * @param mobile
 * @returns {string}
 */
import moment from "moment";
function createPhonePrivacy(mobile) {
  return `${mobile.substring(0, 3)}****${mobile.substring(7)}`;
}

/**
 * 根据native date对象创建可以format的时间对象
 * @param likeDate
 * @param format
 * @returns {string|*}
 */
function createFormatDateByNativeDateObject(likeDate, format = "YYYY-MM-DD") {
  if (!likeDate) return void 0;
  if (likeDate instanceof Date) {
    return moment(likeDate).format(format);
  }
  return likeDate;
}

/**
 * 是否为promise
 * @param likePromise
 */
function isPromise(likePromise) {
  try {
    return (
      ((typeof likePromise === "object" && likePromise !== null) || typeof likePromise === "function") && likePromise && typeof likePromise.then === "function"
    );
  } catch (e) {
    return false;
  }
}

/**
 * hack处理后端参数要求
 * 奇葩传参要求！！！
 * eg：
 * { list: [{name: 1}] } => { list[0].name: 1 }
 * @param obj
 * @returns {{}}
 */
function hackParamsByArray(obj) {
  let _res = {};
  for (const [k, v] of Object.entries(obj)) {
    if (Array.isArray(v)) {
      v.forEach((i, $i) => {
        _res = Object.keys(i).reduce((m, p) => ((m[`${k}[${$i}].${p}`] = i[p]), m), _res);
      });
    } else _res[k] = v;
  }
  return _res;
}

export { createPhonePrivacy, hackParamsByArray, isPromise, createFormatDateByNativeDateObject };
